/**
 * @author flobo
 */

 var Joel = new Class({
	tasksselected:[],
	lastField:false,
	project:'summary',					// initial project after login
	projects:[],						// projects object
	tasklist:{},						// tasklist object
	currentTask:false,
	currentProject:false,
	currentRow:false,						
	currentField:false,					
	lastTask:false,						// previously selected Task
	plugins:{},							// container for plugin classes
	clipboard:false,					// clipboard object
	//user:false,							// container for user details
	templates:false,					// container for template html source
	keysdown:[],  						// container for pressed keys
	updateFieldInt:false,				// field update interval
	api:'api.php',	// URL zum API
	keyEvent:{},						// global object for last key event
	controlkey:Browser.Platform.mac ? 'meta' : 'control', 	// assign the apple key as control equivalent
	interval:false,						// interval for keeping session alive
	
	initialize:function() {
		BC.addListener(this);
		window.addEvent('resize', this.windowResize);
		this.windowResize();
	},
	
	windowResize:function() {
		BC.broadcastMessage('window.resize',[window.getWidth(), window.getHeight()]);	
	},
	
	// THIS HAS TO BE MOVED INTO THE CLASS TASKLIST LATER ON	
	tasklist_resize:function() {
		if ($('tasklist_list')) {
			//setTimeout(function() {
				var dim = $('tasklist_list').getCoordinates();
				$('tasklist_list').style.height = String(Number(window.getHeight()) - Number(dim.top) - 20) + 'px';
			//},100);
		}
	},
	
	/**
	* Main interface function to call methods from the server.
	* If you supply the method name, it will call a method from the Joel class
	* If you supply a method name in this format "classname:methodname" the method will
	* be called in the given class name.
	* 
	* @param {String} method method to be called
	* @param {Object} parameter parameter to be passed to method
	* @param {Function} onComplete function to be called after response from server
	* @param {String} update id of dom tree element to be updated with response from server
	* @param {Bool} async async set "true" to process ajax request ansynchronously
	* @param {Bool} evalReturn async set "true" to evaluate javascript contained in response
	*/
	request:function(method, parameter, onComplete, update, async, evalReturn) {
		var packet = {parameter: parameter};
		var classname = method.split(":");
		
		if (typeof classname[1] != "undefined") {
			packet.method = classname[1];
			packet.classname = classname[0];
			
		} else {
			packet.method = classname[0];
			packet.classname = 'joel';
		}
	
		var query = {
			url:api,
			method: 'post',
			data:'json='+JSON.encode(packet)
		};
		
		if (typeof async != "undefined") { query.async = async; }
		if ($type(update) == 'element') { query.update = update; }
		if ($defined(evalReturn)) { query.evalScripts = true; }
		
		var _parent = this;
		var regex = new RegExp("^error:*");
		query.onFailure = function (res) { BC.broadcastMessage('j.request.error', res); };
		query.onComplete = function (res, text) {
			if(res == 'logout') {
				_parent.logout();
			
			} else if (regex.exec(res)) {
				BC.broadcastMessage('j.request.error',res);
				
			} else {
				if($type(onComplete) == 'function') {
					onComplete(res,text);
				}
			}
		};
		return new Request(query).send();
	},
	
	init:function() {
		BC.broadcastMessage('joel.init');
		project = 'summary';				// initial project after login
		projects = [];						// projects object
		tasklist = {};						// tasklist object
		currentTask = false;
		lastTask = false;					// previously selected Task
		currentRow = false;
		currentField = false;		
		document.title = PROJECT_TITLE;
		keysdown = [];  					// container for pressed keys
		if(this.interval){ clearInterval(this.interval); }
		this.interval = false;
		
		clearTimeout(updateFieldInt);		// field update interval  to be part of task class

		if($defined(user.user_id) && user.user_id) {
			if(user.u_type == 'admin') {
				admin = new Admin();
			}
			
			var loader = new Loader(['joel.getProjects','customerlist.getList'],function() { 
				BC.broadcastMessage('joel.start');
			});
			
			this.interval = window.setInterval(this.intervalFunction, 120000);
			
			getProjects();
			customerlist = new Customerlist();
		}
	},
	
	/**
	 * interval to check connection and keep session alive
	 */
	intervalFunction:function() {
		this.request('init', {'sessid':this.sessid},function(res) {
			var result = JSON.decode(res);
			if(!result.loggedin){ this.logout(); }
		});
	},

	events:function(fnc, param) {
		if (fnc == 'user.logout' || fnc == 'user.login' || fnc == 'user.getdata') {
			this.init();
		}
		else if (fnc == 'tasklist.draw' || fnc == 'window.resize') {
			this.tasklist_resize();
		}
	}
 });